﻿using DevExpress.XtraEditors;
using MesProjectWinform.Equipment.Output;
using MesProjectWinform.Public;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.Equipment.Form.DeviceType
{
    public partial class DeviceTypeForm : DevExpress.XtraEditors.XtraForm
    {
        private int pageIndex = 1; // 当前页码
        private int pageSize = 3; // 每页显示的记录数
        private int totalCount = 0; // 总记录数
        private int totalPages = 0;// 总页数
        public DeviceTypeForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 重新初始化设备类型列表，并设置GridView的列和操作按钮。
        /// </summary>
        public async Task ReInit(string deviceTypeCode = "", string deviceTypeName = "")
        {
            // 异步获取设备类型列表
            List<DeviceTypeOuput> deviceTypeOuputs;
            if(string.IsNullOrEmpty(deviceTypeCode) && string.IsNullOrEmpty(deviceTypeName))
            {
                deviceTypeOuputs = await GetDeviceTypeList();
            }
           
                // 有查询条件，根据条件获取数据
                deviceTypeOuputs = await GetDeviceTypeListByCondition(deviceTypeCode, deviceTypeName);
            

            // 绑定数据到GridControl
            gridControl1.DataSource = deviceTypeOuputs;

            // 获取主视图为GridView
            var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;

            if (gridView != null)
            {
                // 清除现有列，避免重复添加
                gridView.Columns.Clear();

                // 添加各字段对应的可见列
                gridView.Columns.AddVisible("Id", "编号");
                gridView.Columns.AddVisible("DeviceTypeCode", "设备编码");
                gridView.Columns.AddVisible("DeviceTypeName", "设备名称");
                gridView.Columns.AddVisible("DeviceTypeDescription", "设备描述");
                gridView.Columns.AddVisible("CreatedBy", "创建人");

                // 为日期时间列设置格式
                var createdTimeColumn = gridView.Columns.AddVisible("CreatedTime", "创建时间");
                var updatedTimeColumn = gridView.Columns.AddVisible("UpdatedTime", "更新时间");
                // 设置日期时间格式为 yyyy-MM-dd HH:mm:ss
                createdTimeColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                createdTimeColumn.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";

                updatedTimeColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                updatedTimeColumn.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";

                // 添加操作列（用于放置删除按钮）
                var colAction = gridView.Columns.AddVisible("Action", "操作");
                // 设置操作列为非绑定列（Unbound），类型为Object
                colAction.UnboundType = DevExpress.Data.UnboundColumnType.Object;
                // 始终显示按钮
                colAction.ShowButtonMode = DevExpress.XtraGrid.Views.Base.ShowButtonModeEnum.ShowAlways;

                // 创建删除按钮编辑器
                var btnDelete = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
                // 设置按钮文本为“删除”
                btnDelete.Buttons[0].Caption = "删除";
                // 设置按钮样式为Glyph（图标按钮）
                btnDelete.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
                // 隐藏文本编辑框，仅显示按钮
                btnDelete.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
                // 绑定按钮点击事件
                btnDelete.ButtonClick += BtnDelete_ButtonClick;
                // 将按钮编辑器添加到GridControl的仓库项中
                gridControl1.RepositoryItems.Add(btnDelete);
                // 设置操作列的编辑器为删除按钮
                colAction.ColumnEdit = btnDelete;

                //  扩展：添加编辑按钮
                var btnEdit = new DevExpress.XtraEditors.Controls.EditorButton(
                    DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph)
                {
                    Caption = "编辑",
                    Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph
                };
                btnDelete.Buttons.Add(btnEdit); // 这里是给原有btnDelete编辑器追加一个编辑按钮
                // 设置自定义未绑定列数据事件，为操作列赋值
                gridView.CustomUnboundColumnData += (s, e) =>
                {
                    if (e.Column.FieldName == "Action")
                    {
                        // 操作列显示“删除”
                        e.Value = "删除";
                    }
                };
            }
        }

        /// <summary>
        /// 处理GridView中“删除”或“编辑”按钮点击事件。
        /// </summary>
        /// <param name="sender">事件源对象，通常为按钮编辑器</param>
        /// <param name="e">按钮点击事件参数，包含被点击的按钮信息</param>
        private async void BtnDelete_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            // 获取GridView对象
            var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (gridView == null) return;

            // 获取当前选中行的数据对象
            var row = gridView.GetRow(gridView.FocusedRowHandle) as DeviceTypeOuput;
            if (row == null) return;

            // 判断点击的是“删除”按钮
            if (e.Button.Caption == "删除")
            {
                // 弹出确认对话框，确认是否删除
                var confirm = MessageBox.Show($"确定要删除设备类型【{row.DeviceTypeName}】吗？", "确认删除", MessageBoxButtons.YesNo);
                if (confirm != DialogResult.Yes) return;

                // 调用API删除设备类型
                using (var client = new HttpClient())
                {
                    // 发送DELETE请求到后端API
                    var response = await client.DeleteAsync($"http://47.110.243.157:5229/api/DeviceType/DeleteDeviceType?id={row.Id}");
                    if (response.IsSuccessStatusCode)
                    {
                        // 删除成功，提示并刷新列表
                        MessageBox.Show("删除成功！");
                        await ReInit();
                    }
                    else
                    {
                        // 删除失败，提示用户
                        MessageBox.Show("删除失败！");
                    }
                }
            }
            // 判断点击的是“编辑”按钮
            else if (e.Button.Caption == "编辑")
            {
                // 创建编辑窗体
                DeviceTypeEditForm editForm = new DeviceTypeEditForm();
                // 传递设备类型ID给编辑窗体，加载详细信息
                editForm.SetDeviceType(row.Id);
                // 显示编辑窗体，等待用户操作
                if (editForm.ShowDialog() == DialogResult.OK)
                {
                    // 编辑成功后重新加载数据
                    await ReInit();
                }
            }
        }

        /// <summary>
        /// 加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void DeviceTypeForm_Load(object sender, EventArgs e)
        {
           await ReInit();
        }
        /// <summary>
        /// 异步获取设备类型列表的方法
        /// </summary>
        /// <returns></returns>
        private async Task<List<DeviceTypeOuput>> GetDeviceTypeList()
        {
            using (var client = new HttpClient())
            {
                // 调用API获取设备类型分页数据
                var response = await client.GetStringAsync($"http://47.110.243.157:5229/api/DeviceType/GetDeviceTypeList?PageIndex={pageIndex}&PageSize={pageSize}");
                // 反序列化API返回的JSON数据
                var result = JsonConvert.DeserializeObject<ApiPaging<DeviceTypeOuput>>(response);
                totalCount = result.TotalCount; // 获取总记录数
                totalPages = (int)Math.Ceiling((totalCount * 1.0) / pageSize); // 计算总页数
                // 返回分页数据中的设备类型列表
                return result.PageData;
            }
        }

        /// <summary>
        /// 根据条件获取设备类型列表
        /// </summary>
        /// <param name="deviceTypeCode">设备编码（等值查询）</param>
        /// <param name="deviceTypeName">设备名称（模糊查询）</param>
        /// <returns>查询结果列表</returns>
        private async Task<List<DeviceTypeOuput>> GetDeviceTypeListByCondition(string deviceTypeCode, string deviceTypeName)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    // 构建查询参数
                    string queryParams = $"PageIndex={pageIndex}&PageSize={pageSize}"; // 设置较大的PageSize以获取更多结果

                    // 添加设备编码查询条件（等值查询）
                    if (!string.IsNullOrEmpty(deviceTypeCode))
                    {
                        queryParams += $"&DeviceTypeCode={deviceTypeCode}";
                    }

                    // 添加设备名称查询条件（模糊查询）
                    if (!string.IsNullOrEmpty(deviceTypeName))
                    {
                        queryParams += $"&DeviceTypeName={deviceTypeName}";
                    }

                    // 发送请求到API
                    var response = await client.GetStringAsync($"http://47.110.243.157:5229/api/DeviceType/GetDeviceTypeList?{queryParams}");
                    var result = JsonConvert.DeserializeObject<ApiPaging<DeviceTypeOuput>>(response);

                    return result.PageData;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询出错：{ex.Message}");
                return new List<DeviceTypeOuput>(); // 返回空列表
            }
        }
        /// <summary>
        /// 添加按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceTypeAddButton1_Click(object sender, EventArgs e)
        {
            // 创建并显示设备类型新增表单（模态对话框）
            DeviceTypeAddForm deviceTypeAddForm = new DeviceTypeAddForm();
            deviceTypeAddForm.ShowDialog();
            // 如果新增成功（对话框返回OK），则重新加载设备类型列表
            if (deviceTypeAddForm.DialogResult == DialogResult.OK)
            {
                // 重新加载设备类型列表
                DeviceTypeForm_Load(sender, e);
            }
        }

        /// <summary>
        /// 查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void QueryButton2_Click(object sender, EventArgs e)
        {
            // 获取查询条件
            string deviceTypeCode = DeviceTypeCode.Text.Trim();
            string deviceTypeName = DeviceTypeName.Text.Trim();

            // 调用重新初始化方法，传入查询条件
            await ReInit(deviceTypeCode, deviceTypeName);

            // 显示查询结果数量
            var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
            if (gridView != null)
            {
                MessageBox.Show($"查询到 {gridView.RowCount} 条记录");
            }
        }
        /// <summary>
        /// 重置按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ResetButton3_Click(object sender, EventArgs e)
        {
            DeviceTypeName.Text = "";
            DeviceTypeCode.Text = "";

            // 调用重新初始化方法，传入查询条件
            await ReInit();
        }

        /// <summary>
        /// 上一页按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void PrevPageButton4_Click(object sender, EventArgs e)
        {
            if (pageIndex <= 1) 
            {
                MessageBox.Show("已经是第一页了！");
                return;
            }
            pageIndex -= 1;
            await ReInit();
        }
        /// <summary>
        /// 下一页按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void NextPageButton5_Click(object sender, EventArgs e)
        {
            if (pageIndex >= totalPages)
            {
                MessageBox.Show("已经是最后一页了！");
                return;
            }
            pageIndex += 1;
            await ReInit();
        }
       
    }
}